﻿
namespace SalesPages.EntityFrameworkRepository
{

    using Infrastructure.IRepository;
    using System;
    using System.Data;
    using System.Data.Entity;
    using System.Data.Entity.Validation;
    public class EFUnitOfWork : IUnitOfWork, IDisposable
    {
        [ThreadStatic]
        private static Lazy<EFUnitOfWork> s_current;
        private DbContextTransaction transaction;

        public DbContext Context { get; set; }

        public static Lazy<EFUnitOfWork> Current
        {
            get
            {
                return s_current;
            }
            set
            {
                s_current = value;
            }
        }

        public EFUnitOfWork()
        {
            Context = new ET_EnglishFirstContext();
        }

        public EFUnitOfWork(DbContext context)
        {
            Context = context;
        }

        public void BeginTransaction(IsolationLevel isolationLevel)
        {
            transaction = Context.Database.BeginTransaction(isolationLevel);
        }

        public void Commit()
        {
            try
            {
                Context.SaveChanges();
                transaction.Commit();
            }
            catch (DbEntityValidationException dbEx)
            {
                var s = dbEx.EntityValidationErrors;
                throw dbEx;
            }
        }

        public void Rollback()
        {
            transaction.Rollback();
        }

        public void Dispose()
        {
            Context.Dispose();
            Context = null;
        }
    }
}
